import React, { useState, useRef } from 'react'
import { useModel } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import { Space, Image, Button, Radio } from 'antd'
import dayjs from 'dayjs'

export default ({ data }) => {
  const { H5PromotionList, H5SharePromotionList } = useModel('H5Promotion')

  const [pageSize, setPageSize] = useState(5) //  每页数量
  const [currentPage, setCurrentPage] = useState(1) //  当前页码

  // 逾期筛选项
  const [overdueFilter, setOverdueFilter] = useState({
    sort_name: '',
    sort: ''
  })

  const tableRef = useRef()

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    if (data.currentIsOpen) {
      return
    }

    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  const searchColumns = [
    {
      title: '客户姓名',
      dataIndex: 'name',
      hideInTable: true
    },
    {
      title: '订单编号',
      dataIndex: 'order_sn',
      hideInTable: true
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      hideInTable: true
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'dateTimeRange',
      search: {
        transform: value => {
          return {
            start_time: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            end_time: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    }
  ]

  const originColumns = [
    {
      title: '商品信息',
      dataIndex: 'goods_name',
      width: 200,
      align: 'left',
      hideInSearch: true,
      render: (text, record) => (
        <Space>
          <Image width={72} src={record.goods_pic} />
          <div>
            <div>
              <a onClick={() => goProduct(3, record.goods_id, record.merchant_id)}>{text}</a>
            </div>
            <span>套餐：{record.attr_value}</span>
          </div>
        </Space>
      )
    },
    {
      title: '套餐信息',
      width: 100,
      align: 'left',
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div>
            <div>套餐 : {row.attr_value.split('/')[0]}</div>
            <div>内存 : {row.attr_value.split('/')[1]}</div>
          </div>
        )
      }
    },
    {
      title: '客户信息',
      width: 100,
      align: 'left',
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div>
            <div>姓名 : {row.name}</div>
            <div>手机号 : {row.mobile}</div>
            <div>身份证 : {row.cert_no}</div>
            <div>人脸识别 : {row.face_status}</div>
          </div>
        )
      }
    },
    {
      title: '订单信息',
      width: 100,
      align: 'left',
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div>
            <div>订单编号 : {row.order_sn}</div>
            <div>下单时间 : {row.created_at}</div>
          </div>
        )
      }
    },
    {
      title: '渠道归属',
      width: 100,
      align: 'center',
      hideInSearch: true,
      render: (_, row) => {
        return <div>渠道 : {row.plat_from_source}</div>
      }
    },
    {
      title: '订单状态',
      width: 100,
      dataIndex: 'order_status_name',
      align: 'left',
      hideInSearch: true,
      // 订单逾期筛选
      filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
        <div style={{ padding: 8 }}>
          <Radio.Group
            onChange={e => {
              setSelectedKeys(e.target.value)
            }}
            value={selectedKeys}
          >
            <Space direction='vertical'>
              <Radio value={'due_days|desc'}>逾期天数降序</Radio>
              <Radio value={'due_days|asc'}>逾期天数升序</Radio>

              <Radio value={'due_amount|desc'}>逾期金额降序</Radio>
              <Radio value={'due_amount|asc'}>逾期金额升序</Radio>

              <Radio value={'due_number|desc'}>逾期次数降序</Radio>
              <Radio value={'due_number|asc'}>逾期次数升序</Radio>
            </Space>
          </Radio.Group>
          <div style={{ marginTop: 8 }}>
            <Button
              size='small'
              type='text'
              onClick={() => {
                clearFilters()
                confirm()
                setOverdueFilter({ sort_name: '', sort: '' })
                setTimeout(() => {
                  tableRef.current.reload()
                }, 100)
              }}
              style={{ marginRight: 8, color: 'rgba(0, 0, 0, 0.25)' }}
            >
              重置
            </Button>
            <Button
              type='primary'
              size='small'
              onClick={() => {
                confirm()
                const [sort_name, sort] = selectedKeys.split('|')
                setOverdueFilter({ sort_name, sort })
                setTimeout(() => {
                  tableRef.current.reload()
                }, 100)
              }}
            >
              确定
            </Button>
          </div>
        </div>
      ),
      render: (_, row) => {
        let { order_status_name, due_days, due_amount, due_number, status } = row
        return (
          <div>
            <div style={{ fontWeight: 'bold' }}>{order_status_name}</div>
            {/* 4100 已逾期 */}
            {status === 4100 && (
              <div style={{ color: '#ff4d4f' }}>
                <div>逾期天数 : {due_days}</div>
                <div>逾期金额 : ¥{due_amount}</div>
                <div>逾期次数 : {due_number}</div>
              </div>
            )}
          </div>
        )
      }
    },
    {
      title: '租金信息',
      width: 100,
      align: 'left',
      hideInSearch: true,
      render: (_, row) => {
        return (
          <div>
            <div>总期数 : {row.lease_term} 期</div>
            <div>总租金 : ¥{row.total_price}</div>
          </div>
        )
      }
    },
    ...searchColumns
  ]

  return (
    <ProTable
      actionRef={tableRef}
      request={async params => {
        const param = {
          page: params.current,
          page_size: params.pageSize,
          id: data.id,
          type: data.type,
          // 逾期筛选项
          sort_name: overdueFilter.sort_name,
          sort: overdueFilter.sort,
          ...params
        }

        setCurrentPage(params.current)
        setPageSize(params.pageSize)

        let res = null

        if (data.currentIsOpen) {
          res = await H5SharePromotionList(param)
        } else {
          res = await H5PromotionList(param)
        }

        return {
          data: res.data,
          success: true,
          total: res.total
        }
      }}
      pagination={{
        pageSize: pageSize,
        current: currentPage,
        showSizeChanger: true
      }}
      options={false}
      scroll={{ x: 'max-content' }}
      rowKey='created_at'
      columns={originColumns}
      search={{
        defaultCollapsed: false,
        labelWidth: 'auto',
        span: 6
      }}
    />
  )
}
